﻿<%@ WebHandler Language="C#" Class="ZSIssueCollectMaterialHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
/// <summary>
/// add by longb 2022-05-16
/// 去封、集件报工功能
/// 
/// </summary>
public class ZSIssueCollectMaterialHandler : IHttpHandler,IRequiresSessionState {
    
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    //uLMSIssueERPMaterialIbusiness m_issueData= uMESBusinessFactory.instance.GetuLMSIssueERPMaterialObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    SealAndIssueBusiness m_issueData=new SealAndIssueBusiness();
    SendRequestBusiness m_sendData = new SendRequestBusiness();
    string PartType=string.Empty; 
    #region 页面初始化
    public void ProcessRequest (HttpContext context) {
        try
        {
            PartType=context.Request["type"].ToString();
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetTaskOrderData": //查询任务单信息
                    GetTaskOrderData(context);
                    break;
                case "GetBigSmallData": //查询大小件信息
                    GetBigSmallData(context);
                    break;
                case "GetWorkFlowData": //查询工序信息
                    GetWorkFlowData(context);
                    break;
                case "SaveIssueERPMaterialConfirmation": //去封、集件报工
                    SaveIssueERPMaterialConfirmation(context);
                    break;
                case "GetProgressData": //查看进度准备
                    GetProgressData(context);
                    break;    
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    #endregion

    #region 方法【查询】
    /// <summary>
    /// 查询任务单信息
    /// </summary>
    /// <param name="context"></param>
	public void GetTaskOrderData(HttpContext context)
    {
       string pageSize=context.Request["pageSize"].ToString();
       string pageNumber=context.Request["pageNumber"].ToString();
       DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
       var Condition=new Dictionary<string,string>();
            Condition.Add("ContainerNo", dt.Rows[0]["ContainerNo"].ToString());
            Condition.Add("Machine", dt.Rows[0]["Machine"].ToString());
            Condition.Add("MfgOrdername", dt.Rows[0]["MfgOrdername"].ToString());
            Condition.Add("WorkFlowType", dt.Rows[0]["WorkFlowType"].ToString());
            Condition.Add("HasBom", dt.Rows[0]["HasBom"].ToString());
            //Condition.Add("PartType", PartType);
            Condition.Add("PageSize", pageSize);
            Condition.Add("CurrentPageIndex", pageNumber);
            uMESProcessResult result = new uMESProcessResult();
            if (dt.Columns.Contains("TEMP")) {
                result = m_issueData.GetTempContainerNo(Condition);
            }
            else
            {
                result=m_issueData.GetCollectContainerNo(Condition);
            }
       if (result.Result) result.Message = "查询成功";
       context.Response.Write(JsonConvert.SerializeObject(result));
    } 
    /// <summary>
    /// 查询大小件信息
    /// </summary>
    /// <param name="context"></param>
    public void GetBigSmallData(HttpContext context)
    {
       string strNoList=context.Request["strNoList"].ToString();
       string workflowstepid=context.Request["workflowstepid"].ToString();
       DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
       var Condition=new Dictionary<string,string>();
            Condition.Add("ContainerNo", dt.Rows[0]["ContainerNo"].ToString());//任务单号
            Condition.Add("ContainerNoList", strNoList);//
            Condition.Add("Machine", dt.Rows[0]["Machine"].ToString());//发动机号
            Condition.Add("PartType", PartType);//0:去封，1:集件
            Condition.Add("workflowstepid", workflowstepid);
            Condition.Add("ContainerID", context.Request["containerID"].ToString());
            Condition.Add("mfgorderid", context.Request["mfgorderid"].ToString());
            Condition.Add("mProduct", context.Request["mproduct"].ToString());
       uMESProcessResult result=new uMESProcessResult();

       result.DBTable=m_issueData.GetCollectIssue(Condition);
       if (result.DBTable.Rows.Count>0) {result.Message = "查询成功"; result.Result=true;}
       context.Response.Write(JsonConvert.SerializeObject(result));
    } 
    /// <summary>
    /// //查询工序信息
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkFlowData(HttpContext context){
         string WorkFlowId=context.Request["workflowid"].ToString();
        uMESProcessResult result=new uMESProcessResult();
        result.DBTable=m_issueData.GetWorkFlowData(WorkFlowId);
        result.Result=true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 去封、集件报工
    /// </summary>
    /// <param name="context"></param>
    public void SaveIssueERPMaterialConfirmation(HttpContext context){
        uMESProcessResult result=new uMESProcessResult();
        //获取插入资料表List
        var IssueERPMaterialConfirmationList=GetIssueERPMaterialConfirmationList(context);
        result.Result=DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(IssueERPMaterialConfirmationList);
        if(result.Result){
            //更新任务单--去封、集件齐套率--ICFULLSETRATE
            var strFirstSecondIssue = m_ContainerObj.CheckFirstSecondIssueNew(context.Request["CONTAINERID"].ToString());//判断是初装（1）、检装（2）
            //DataTable QTdt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable("SELECT " + (strFirstSecondIssue == "1" ? "GETCONTAINER_ICQTL(e.CONTAINERID)" : "GETCONTAINER_JZICQTL(e.containerid,e.containerno)") + "QTL FROM ENGINEPARTPLAN e WHERE e.CONTAINERID ='" + context.Request["CONTAINERID"].ToString() + "'");
            DataTable QTdt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable("SELECT GETCONTAINER_ICQTL(e.CONTAINERID,e.MFGORDERID) QTL FROM ENGINEPARTPLAN e WHERE e.CONTAINERID ='" + context.Request["CONTAINERID"].ToString() + "'");
            if (QTdt.Rows.Count > 0)
            {
                List<ExcuteEntity> UPList = new List<ExcuteEntity>();
                var upEntity = new ExcuteEntity("ENGINEPARTPLAN", ExcuteEntity.ExcuteTypeEnum.update);
                List<FieldEntity> upList = new List<FieldEntity>();
                upList.Add(new FieldEntity("ICFULLSETRATE", QTdt.Rows[0]["QTL"].ToString(), FieldEntity.FieldTypeEnum.Str));
                upEntity.ExcuteFileds = upList;
                List<FieldEntity> whereList = new List<FieldEntity>();
                whereList.Add(new FieldEntity("CONTAINERID", context.Request["CONTAINERID"].ToString(), FieldEntity.FieldTypeEnum.Str));
                upEntity.WhereFileds = whereList;
                UPList.Add(upEntity);
               var up= DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(UPList);
            }
            //获取插入工时表List
            var ContainerSteptimeSheetList=GetContainerSteptimeSheetList(context);
            var resulttt2=DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(ContainerSteptimeSheetList);
            if(!resulttt2){
                result.Message=(PartType=="0"?"去封":"集件")+"报工完成，工时记录异常";
            }else{
                result.Message=(PartType=="0"?"去封":"集件")+"完成";
            }
        }else{
            result.Message=(PartType=="0"?"去封":"集件")+"失败";
        }
       context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取插入资料表List
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public  List<ExcuteEntity> GetIssueERPMaterialConfirmationList(HttpContext context){
        List<ExcuteEntity> List = new List<ExcuteEntity>();
         DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
         var strFirstSecondIssue = m_ContainerObj.CheckFirstSecondIssueNew(context.Request["CONTAINERID"].ToString());//判断是初装（1）、检装（2）  
         for(var i=0;i<dt.Rows.Count;i++){
             if (Convert.ToInt32(dt.Rows[i]["CHANGEQTY"].ToString()) > 0)
             {
                var InsertEntity = new ExcuteEntity("issueerpmaterialconfirmation", ExcuteEntity.ExcuteTypeEnum.insert);
                List<FieldEntity> InsertList = new List<FieldEntity>();
                InsertList.Add(new FieldEntity("confirmqty", dt.Rows[i]["CHANGEQTY"].ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("createdate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
                InsertList.Add(new FieldEntity("employeeid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("issueerpmaterialconfirmationid", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("issueerpmaterialid",dt.Rows[i]["issueerpmaterialid"].ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("note", strFirstSecondIssue, FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("mfgorderid", context.Request["mfgorderid"].ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertEntity.ExcuteFileds = InsertList;
                List.Add(InsertEntity);
             }
         }
        return List;
    }
    /// <summary>
    /// 获取插入工时表List
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public  List<ExcuteEntity> GetContainerSteptimeSheetList(HttpContext context){
       List<ExcuteEntity> List = new List<ExcuteEntity>();
          DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
         for(var i=0;i<dt.Rows.Count;i++){
              //判断任务单批次是属于一次集件or二次集件，获取集件工步/工序，判断发动机集件工时是否已经插入
            var FirstSecondIssue=m_ContainerObj.CheckFirstSecondIssueNew(dt.Rows[0]["ContainerId"].ToString()).ToString();
            if(string.IsNullOrWhiteSpace(FirstSecondIssue)){continue;}
            string WorkFlowStepId= string.Empty;
            string StepInfoId = string.Empty;
            string WorkFlowStepName = string.Empty;
            string StepInfoName = string.Empty;
            string Durationperunit = "0";
            DataTable dtt= m_issueData.GetCollectWorkFlowData(dt.Rows[0]["WorkFlowId"].ToString(),context.Request["type"].ToString());
            if(dtt.Rows.Count>0){
               #region 判断是第一次报工还是第二次
                if(FirstSecondIssue == "1"){
                    WorkFlowStepId = dtt.Rows[0]["WorkFlowStepId"].ToString();
                    StepInfoId = dtt.Rows[0]["StepInfoId"].ToString();
                    WorkFlowStepName = dtt.Rows[0]["WorkFlowStepName"].ToString();
                    StepInfoName = dtt.Rows[0]["StepInfoName"].ToString();
                    Durationperunit = dtt.Rows[0]["Durationperunit"].ToString();
                }
                else if (FirstSecondIssue == "2"){
                    if (dtt.Rows.Count >= 1){
                        WorkFlowStepId = dtt.Rows[0]["WorkFlowStepId"].ToString();
                        StepInfoId = dtt.Rows[0]["StepInfoId"].ToString();
                        WorkFlowStepName = dtt.Rows[0]["WorkFlowStepName"].ToString();
                        StepInfoName = dtt.Rows[0]["StepInfoName"].ToString();
                        Durationperunit = dtt.Rows[0]["Durationperunit"].ToString();
                    }
                }
                if(string.IsNullOrWhiteSpace(StepInfoId)){
                    continue;
                }
                #endregion
                //判断工时表资料是否存在
               #region 判断工时表资料是否存在
               var para=new Dictionary<string,string>();
                   para.Add("MachineName", dt.Rows[i]["MachineName"].ToString());
                   para.Add("StepInfoId", StepInfoId);
                   para.Add("WorkFlowStepId", WorkFlowStepId);
               var CheckResult= m_issueData.CheckContainerSteptimeSheet(para);
                if(CheckResult){
                     continue;
                }
                #endregion

               #region 组装工时表实体数据
		        var InsertEntity = new ExcuteEntity("CONTAINERSTEPTIMESHEET", ExcuteEntity.ExcuteTypeEnum.insert);
                List<FieldEntity> InsertList = new List<FieldEntity>();
                InsertList.Add(new FieldEntity("createdate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));//创建日期--
                InsertList.Add(new FieldEntity("workcenterid", m_UserInfo.WorkCenterID.ToString(), FieldEntity.FieldTypeEnum.Str));//工区ID--
                InsertList.Add(new FieldEntity("workerid", m_UserInfo.EmployeeID.ToString(), FieldEntity.FieldTypeEnum.Str));//操作工ID--
                InsertList.Add(new FieldEntity("teamid",m_UserInfo.TeamID.ToString(), FieldEntity.FieldTypeEnum.Str));//班组ID--
                InsertList.Add(new FieldEntity("containersteptimesheetid",Guid.NewGuid().ToString(),FieldEntity.FieldTypeEnum.Str));//唯一ID--
                InsertList.Add(new FieldEntity("workflowstepname",WorkFlowStepName,FieldEntity.FieldTypeEnum.Str));//工序名称
                InsertList.Add(new FieldEntity("workflowstepid",WorkFlowStepId,FieldEntity.FieldTypeEnum.Str));//工序ID
                InsertList.Add(new FieldEntity("Stepinfoid",StepInfoId,FieldEntity.FieldTypeEnum.Str));//工步ID
                InsertList.Add(new FieldEntity("containername",dt.Rows[i]["containername"].ToString(),FieldEntity.FieldTypeEnum.Str));//流水卡号--
                InsertList.Add(new FieldEntity("containerid",dt.Rows[i]["containerid"].ToString(),FieldEntity.FieldTypeEnum.Str));//流水卡ID--
                InsertList.Add(new FieldEntity("totalduration",Durationperunit,FieldEntity.FieldTypeEnum.Str));//合计工时--
                InsertList.Add(new FieldEntity("FactoryID",m_UserInfo.FactoryID.ToString(),FieldEntity.FieldTypeEnum.Str));//分厂ID--
                InsertList.Add(new FieldEntity("Qty","1",FieldEntity.FieldTypeEnum.Str));//报工数--
                InsertList.Add(new FieldEntity("SCRAPQTY","0",FieldEntity.FieldTypeEnum.Str));//报废数--
                InsertEntity.ExcuteFileds = InsertList;
                List.Add(InsertEntity);
	            #endregion
            }
         
         }
       return List;
     }
	#endregion

    public void GetProgressData(HttpContext context){
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        string workflowstepid = context.Request["id"].ToString();
        string ContainerNo = context.Request["ContainerNo"].ToString();
        string ContainerID = context.Request["ContainerID"].ToString();//add by longb 2023-01-16
        var orderContainers = JsonConvert.SerializeObject(context.Session["wgResult"]);
        if (!string.IsNullOrWhiteSpace(orderContainers))
        {
            result.ReturnData = context.Session["wgResult"];
            var Condition = new Dictionary<string, string>();
            Condition.Add("ContainerNo", ContainerNo);//任务单号
            Condition.Add("ContainerID", ContainerID);//任务单ID //add by longb 2023-01-16
            Condition.Add("workflowstepid", workflowstepid);
            var par=(Dictionary<string, string>)(context.Session["wgResult"]);
            Condition.Add("mfgorderid", par == null ? context.Request["mfgorderid"].ToString() : par["mfgorderid"]);
            DataTable dt=m_issueData.GetProgressData(Condition);
            DataView dv=dt.DefaultView;
            dv.RowFilter = "parttype=0";
            DataTable big= dv.ToTable();
            big.TableName = "bigTable";
            dv.RowFilter = "parttype=1";
            DataTable small = dv.ToTable();
            small.TableName = "smallTable";
            DataSet ds = new DataSet();
            ds.Tables.Add(big);
            ds.Tables.Add(small);
            Condition.Add("TransportType", "1");
            DataTable tools= m_sendData.GetZsRequiredToolsTransport(Condition);
            tools.TableName = "toolsTable";
            ds.Tables.Add(tools);
            DataTable auxMaterial = m_sendData.GetWorkFlowStepAuxMaterialData(Condition);
            auxMaterial.TableName = "auxMaterialTable";
            ds.Tables.Add(auxMaterial);
            result.DBDataSet = ds;
            
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}